package no.uib.hplims.tools;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.vaadin.appfoundation.persistence.facade.FacadeFactory;

import no.uib.hplims.models.MyOrder;
import no.uib.hplims.models.Peptide;

public class ExportOrder {

	public ExportOrder() {

	}

	/**
	 * Creates a tab separated file with all order information.
	 * 
	 * @param order Order to export to file
	 * @return Tab separated file with order information
	 */
	public File createFile(MyOrder order) {
		File f = null;
		List<Peptide> peptides = getPeptidesInOrder(order);
		try {
			// Create file
			f = new File("Order " + order.getId() + ".txt");
			FileWriter fstream = new FileWriter(f);
			//FileWriter fstream = new FileWriter("Order " + order.getId() + ".txt");
			BufferedWriter out = new BufferedWriter(fstream);
			out.write("UniProt Accession Number\tSequence\tPeptide Name\n");
			Iterator<Peptide> it = peptides.iterator();
			while (it.hasNext()) {
				Peptide p = it.next();
				String s = "";
				s += p.getUniProtAccession() + "\t";
				s += p.getPeptideSequence() + "\t";
				s += p.getPeptideName();
				s += "\n";
				out.append(s);
			}
			// Close the output stream
			out.close();
			return f;
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
			return null;
		}
	}
	
	/**
	 * @param order
	 * @return List of all peptides in order
	 */
	private List<Peptide> getPeptidesInOrder(MyOrder order) {
		String query = "SELECT p FROM Peptide AS p WHERE p.belongsToOrder=:order";
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("order", order);
		List<Peptide> peptides = FacadeFactory.getFacade().list(query, parameters);
		System.out.println("Found in order: " + peptides.size());
		return peptides;
	}

}
